// 默认设置
const DEFAULT_SETTINGS = {
  autoSave: true,
  autoSaveInterval: 30,
  showTodoScroll: true,  // 添加默认显示滚动条设置
  noteFloatOpacity: 80   // 添加默认透明度设置
};

const noteRepository = window.markAnything.noteRepository;
const utils = window.markAnything.utils;
const todoRepository = window.markAnything.todoRepository;
const stickyRepository = window.markAnything.stickyRepository;  

// 当前设置
let currentSettings = { ...DEFAULT_SETTINGS };

// 加载设置
async function loadSettings() {
  try {
    const settings = await chrome.storage.sync.get(['showTodoScroll', 'noteFloatOpacity']);
    currentSettings.showTodoScroll = settings.showTodoScroll ?? DEFAULT_SETTINGS.showTodoScroll;
    currentSettings.noteFloatOpacity = settings.noteFloatOpacity ?? DEFAULT_SETTINGS.noteFloatOpacity;
    console.log('Loaded settings:', currentSettings);
    applyTodoScrollSettings();
  } catch (error) {
    console.error('Error loading settings:', error);
    // 使用默认设置
    currentSettings = { ...DEFAULT_SETTINGS };
  }
}

// 监听设置变化
chrome.storage.onChanged.addListener((changes, namespace) => {
  if (namespace === 'sync' && changes.showTodoScroll) {
    currentSettings.showTodoScroll = changes.showTodoScroll.newValue;
    console.log('Settings changed:', currentSettings);
    applyTodoScrollSettings();
  }
});

// 应用待办滚动条设置
function applyTodoScrollSettings() {
  const container = document.querySelector('.todo-scrollbar-container');
  if (!container) {
    // 如果容器不存在且设置为显示，则创建它
    if (currentSettings.showTodoScroll) {
      todoRepository.createTodoScrollbar();
    }
    return;
  }

  if (currentSettings.showTodoScroll) {
    // 如果设置为显示，则更新内容
    todoRepository.updateTodoScrollbar();
  } else {
    // 如果设置为隐藏，则隐藏滚动条并移除边距
    container.style.display = 'none';
    document.body.style.marginTop = '0';
    const floatingButtons = document.querySelector('.floating-buttons-container');
    if (floatingButtons) floatingButtons.style.marginTop = '0';
    const leftNote = document.querySelector('.left-note-container');
    if (leftNote) leftNote.style.marginTop = '0';
  }
}

// 初始化函数
async function initialize() {
  try {
    // 先加载设置
    await loadSettings();
    
    // 创建浮动按钮
    await createFloatingButtons();
    
    // 创建滚动条（如果设置允许）
    if (currentSettings.showTodoScroll) {
      await todoRepository.createTodoScrollbar();
    }
  } catch (error) {
    console.error('初始化失败，准备重试:', error);
    // 如果初始化失败，等待一段时间后重试
    setTimeout(initialize, 1000);
  }
}

// 统一的初始化策略
function initializeExtension() {
  // 如果不是最外层窗口，则不初始化
  if (window !== window.top) {
    return;
  }

  // 如果页面还在加载中，等待DOMContentLoaded
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
      setTimeout(initialize, 100);
    });
  } else {
    // 页面已经加载完成，直接初始化
    setTimeout(initialize, 100);
  }

  // 为了处理单页应用(SPA)的情况，监听 URL 变化
  let lastUrl = location.href;
  new MutationObserver(() => {
    const url = location.href;
    if (url !== lastUrl) {
      lastUrl = url;
      setTimeout(initialize, 100);
    }
  }).observe(document, { subtree: true, childList: true });
}

// 启动初始化
initializeExtension();

// 修改现有的createFloatingButtons函数
async function createFloatingButtons() {
  return new Promise(async (resolve) => {
    try {
      // 检查是否已存在按钮容器
      const existingContainer = document.querySelector('#mark-anything-container');
      if (existingContainer) {
        resolve();
        return;
      }

      // 创建一个根容器
      const rootContainer = document.createElement('div');
      rootContainer.id = 'mark-anything-container';
      
      // 创建 shadow DOM
      const shadow = rootContainer.attachShadow({ mode: 'closed' });

      // 创建样式
      const style = document.createElement('style');
      style.textContent = `
        .floating-buttons-container {
          position: fixed;
          right: 20px;
          top: 100px;
          display: flex;
          flex-direction: column;
          gap: 6px;
          z-index: 2147483647;
          background: rgba(255, 255, 255, 0.98);
          padding: 8px;
          border-radius: 16px;
          box-shadow: 0 4px 24px rgba(0, 0, 0, 0.12);
          transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
          opacity: ${(currentSettings.noteFloatOpacity || DEFAULT_SETTINGS.noteFloatOpacity) / 100};
          cursor: move;
          user-select: none;
          touch-action: none;
          transform-origin: top center;
          backdrop-filter: blur(8px);
          border: 1px solid rgba(230, 230, 230, 0.7);
        }

        .floating-buttons-container.collapsed {
          padding: 4px;
          height: 42px;
          overflow: hidden;
          border-radius: 12px;
          background: rgba(255, 255, 255, 0.95);
          cursor: pointer;
        }

        .floating-buttons-container.collapsed .floating-button:not(.collapse-button) {
          opacity: 0;
          transform: translateY(-20px);
          pointer-events: none;
        }

        .collapse-button {
          width: 100%;
          height: 32px;
          min-width: 130px;
          padding: 0 10px;
          border: none;
          background: rgba(248, 248, 248, 0.95);
          cursor: pointer;
          display: flex;
          align-items: center;
          gap: 6px;
          border-radius: 10px;
          z-index: 1;
          color: #666;
          transition: all 0.2s ease;
          margin-bottom: 2px;
          font-size: 13px;
        }

        .floating-buttons-container.collapsed .collapse-button {
          height: 100%;
          margin: 0;
          background: rgba(250, 250, 250, 0.98);
          pointer-events: none;
        }

        .collapse-button:hover {
          background: rgba(240, 240, 240, 0.95);
          color: #333;
        }

        .collapse-button-logo {
          font-size: 15px;
          color: #2196F3;
          display: flex;
          align-items: center;
        }

        .collapse-button-text {
          flex-grow: 1;
          text-align: center;
          padding-right: 20px;
          font-weight: 500;
        }

        @media print {
          .floating-buttons-container {
            display: none !important;
          }
        }

        .floating-buttons-container.dragging {
          opacity: 0.8;
          transition: none;
          cursor: grabbing;
        }

        .floating-buttons-container:hover {
          opacity: 1;
        }

        .floating-button {
          display: flex;
          align-items: center;
          gap: 8px;
          padding: 10px 14px;
          border: none;
          border-radius: 10px;
          background: white;
          cursor: pointer;
          transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
          margin: 0;
          width: auto;
          height: auto;
          font-family: system-ui, -apple-system, sans-serif;
          color: #333;
          pointer-events: auto;
          border: 1px solid rgba(230, 230, 230, 0.7);
          opacity: 1;
          transform: translateY(0);
          min-width: 110px;
        }

        .floating-button:hover {
          transform: translateX(-5px);
          background: rgba(250, 250, 250, 0.95);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        }

        .button-icon {
          font-size: 18px;
          line-height: 1;
          transition: transform 0.2s ease;
        }

        .floating-button:hover .button-icon {
          transform: scale(1.1);
        }

        .button-label {
          font-size: 14px;
          white-space: nowrap;
          font-weight: 500;
          color: #444;
        }

        .floating-button.tools-button {
          margin-top: 4px;
          border-top: 1px solid rgba(0, 0, 0, 0.06);
          padding-top: 12px;
        }
        
        .floating-button.tools-button .button-icon {
          color: #2196F3;
        }
        
        .floating-button.tools-button:hover .button-icon {
          color: #1976D2;
        }
      `;

      // 创建主文档的打印样式
      const mainStyle = document.createElement('style');
      mainStyle.textContent = `
        @media print {
          #mark-anything-container {
            display: none !important;
          }
          .selection-menu {
            display: none !important;
          }
          .todo-scrollbar-container {
            display: none !important;
          }
        }
      `;
      document.head.appendChild(mainStyle);

      // 创建按钮容器
      const container = document.createElement('div');
      container.className = 'floating-buttons-container';
      container.style.visibility = 'hidden';

      // 创建折叠按钮
      const collapseButton = document.createElement('button');
      collapseButton.className = 'collapse-button';
      collapseButton.innerHTML = `
        <span class="collapse-button-logo">📌</span>
        <span class="collapse-button-text">收起面板</span>
      `;
      collapseButton.title = '展开/收起工具栏';
      
      // 修改点击处理逻辑
      const toggleCollapse = (e) => {
        e.stopPropagation();
        const isCollapsed = container.classList.toggle('collapsed');
        const buttonText = collapseButton.querySelector('.collapse-button-text');
        buttonText.textContent = isCollapsed ? '展开面板' : '收起面板';
        chrome.storage.local.set({ 'floatingButtonsCollapsed': isCollapsed });
      };

      collapseButton.addEventListener('click', toggleCollapse);
      
      // 为收起状态添加容器级别的点击处理
      container.addEventListener('click', (e) => {
        if (container.classList.contains('collapsed')) {
          toggleCollapse(e);
        }
      });

      // 从存储中恢复折叠状态
      chrome.storage.local.get(['floatingButtonsCollapsed'], (result) => {
        if (result.floatingButtonsCollapsed) {
          container.classList.add('collapsed');
          const buttonText = collapseButton.querySelector('.collapse-button-text');
          buttonText.textContent = '展开面板';
        }
      });

      container.insertBefore(collapseButton, container.firstChild);

      // 从存储中恢复位置并创建按钮
      await new Promise((positionResolve) => {
        chrome.storage.local.get(['floatingButtonsPosition'], (result) => {
          if (result.floatingButtonsPosition) {
            const { right, top } = result.floatingButtonsPosition;
            container.style.right = right;
            container.style.top = top;
            container.style.transform = 'none';
          }
          
          const setButtonLoading = (button, isLoading) => {
            if (isLoading) {
              button.disabled = true;
              button.style.opacity = '0.6';
              button.style.cursor = 'wait';
              const originalText = button.getAttribute('title');
              button.setAttribute('data-original-title', originalText);
              button.setAttribute('title', '处理中...');
            } else {
              button.disabled = false;
              button.style.opacity = '';
              button.style.cursor = '';
              const originalText = button.getAttribute('data-original-title');
              if (originalText) {
                button.setAttribute('title', originalText);
                button.removeAttribute('data-original-title');
              }
            }
          };

          // 创建按钮
          const buttonConfigs = [
            { icon: '✓', label: '待办' },
            { icon: '📝', label: '便签' },
            { icon: '📝', label: '笔记' },
            { icon: '📋', label: '收藏' },
            { icon: '📄', label: 'PDF', action: () => {
              window.print();
            }},
            { icon: '🔲', label: '二维码' },
            { icon: '🛠️', label: '工具箱', className: 'tools-button', action: () => {
              chrome.runtime.sendMessage({ action: 'openToolsPage' });
            }}
          ];

          buttonConfigs.forEach((config, index) => {
            const button = document.createElement('button');
            button.className = `floating-button ${config.className || ''}`;
            button.innerHTML = `
              <span class="button-icon">${config.icon}</span>
              <span class="button-label">${config.label}</span>
            `;

            // 为按钮添加点击事件
            button.addEventListener('click', async (e) => {
              e.stopPropagation();
              if (config.action) {
                config.action();
              } else if (index === 0) {
                todoRepository.showTodoEditor();
              } else if (index === 1) {
                stickyRepository.showStickyNoteEditor();
              } else if (index === 2) {
                noteRepository.showNoteEditor();
              } else if (index === 3) {
                try {
                  setButtonLoading(button, true);
                  const pageContent = document.title + '\n' + 
                    Array.from(document.querySelectorAll('h1, h2, h3, p'))
                      .map(el => el.textContent.trim())
                      .filter(text => text.length > 0)
                      .slice(0, 10)
                      .join('\n');

                  const response = await chrome.runtime.sendMessage({
                    action: 'addBookmark',
                    title: document.title,
                    url: window.location.href,
                    pageContent: pageContent
                  });
                  
                  if (response.error) {
                    utils.showNotification(response.error, true);
                  } else if (response.exists) {
                    utils.showNotification(`书签已存在于 ${response.parentTitle} 文件夹中`);
                  } else if (response.success) {
                    utils.showNotification(`已添加到 ${response.folderPath} 文件夹`);
                  }
                } catch (error) {
                  console.error('添加书签失败:', error);
                  utils.showNotification('添加书签失败', true);
                } finally {
                  setButtonLoading(button, false);
                }
              } else if (index === 5) {
                window.markAnything.qrcodeHandler.showQRCode();
              }
            });

            container.appendChild(button);
          });

          // 添加拖拽功能
          let isDragging = false;
          let currentX;
          let currentY;
          let initialX;
          let initialY;
          let xOffset = 0;
          let yOffset = 0;

          const getPointerPosition = (e) => {
            // 处理触摸事件和鼠标事件
            const point = e.touches ? e.touches[0] : e;
            return {
              clientX: point.clientX,
              clientY: point.clientY
            };
          };

          const dragStart = (e) => {
            if (e.target.closest('.floating-button')) return; // 如果点击的是按钮，不开始拖拽
            
            const point = getPointerPosition(e);
            const rect = container.getBoundingClientRect();
            initialX = point.clientX - rect.left;
            initialY = point.clientY - rect.top;
            
            if (e.target === container) {
              isDragging = true;
              container.classList.add('dragging');
            }
          };

          const drag = (e) => {
            if (isDragging) {
              e.preventDefault();
              
              const point = getPointerPosition(e);
              const x = point.clientX - initialX;
              const y = point.clientY - initialY;
              
              // 确保不会拖出视窗
              const containerWidth = container.offsetWidth;
              const containerHeight = container.offsetHeight;
              const maxX = window.innerWidth - containerWidth;
              const maxY = window.innerHeight - containerHeight;
              
              currentX = Math.min(Math.max(0, x), maxX);
              currentY = Math.min(Math.max(0, y), maxY);
              
              const right = `${window.innerWidth - currentX - containerWidth}px`;
              const top = `${currentY}px`;
              
              container.style.right = right;
              container.style.top = top;
              container.style.transform = 'none';

              // 保存位置到存储
              chrome.storage.local.set({
                floatingButtonsPosition: { right, top }
              });
            }
          };

          const dragEnd = () => {
            if (isDragging) {
              isDragging = false;
              container.classList.remove('dragging');
            }
          };

          // 鼠标事件
          container.addEventListener('mousedown', dragStart);
          document.addEventListener('mousemove', drag);
          document.addEventListener('mouseup', dragEnd);

          // 触摸事件
          container.addEventListener('touchstart', dragStart, { passive: false });
          document.addEventListener('touchmove', drag, { passive: false });
          document.addEventListener('touchend', dragEnd);
          document.addEventListener('touchcancel', dragEnd);

          // 在所有初始化完成后显示容器
          requestAnimationFrame(() => {
            container.style.visibility = 'visible';
          });
          
          positionResolve();
        });
      });

      // 将样式和容器添加到 shadow DOM
      shadow.appendChild(style);
      shadow.appendChild(container);

      // 将根容器添加到页面
      document.body.appendChild(rootContainer);

      // 添加持久性检查
      const checkInterval = setInterval(() => {
        const container = document.querySelector('#mark-anything-container');
        if (!container || !container.isConnected) {
          console.log('按钮容器被移除，重新创建');
          clearInterval(checkInterval);
          createFloatingButtons();
        }
      }, 1000);

      resolve();
    } catch (error) {
      console.error('创建浮动按钮时发生错误:', error);
      resolve();
    }
  });
}

// 修改添加待办的函数，添加滚动条更新
const originalAddTodo = todoRepository.addTodo;
window.addTodo = async function(content) {
  const id = await originalAddTodo(content);
  await todoRepository.updateTodoScrollbar();
  return id;
};

// 修改更新待办状态的函数，添加滚动条更新
const originalToggleTodoStatus = todoRepository.toggleTodoStatus;
window.toggleTodoStatus = async function(id) {
  await originalToggleTodoStatus(id);
  await todoRepository.updateTodoScrollbar();
};

// 修改删除待办的函数，添加滚动条更新
const originalDeleteTodo = todoRepository.deleteTodo;
window.deleteTodo = async function(id) {
  await originalDeleteTodo(id);
  await todoRepository.updateTodoScrollbar();
};

// 修改添加便签的函数
const originalAddStickyNote = window.addStickyNote;
window.addStickyNote = async function(content) {
  const note = await originalAddStickyNote(content);
  return note;
};

// 修改删除便签的函数
const originalDeleteStickyNote = window.deleteStickyNote;
window.deleteStickyNote = async function(id) {
  await originalDeleteStickyNote(id);
};

// 创建选择文本后的浮动菜单
function createSelectionMenu() {
  const menu = document.createElement('div');
  menu.className = 'selection-menu';
  
  const buttons = [
    { icon: '✓', label: '加入待办', action: async () => {
      const selectedText = window.getSelection().toString().trim();
      try {
        await todoRepository.addTodo(selectedText);
        await todoRepository.updateTodoScrollbar();
        utils.showNotification('已添加到待办');
      } catch (error) {
        utils.showNotification('添加待办失败', true);
      }
    }},
    { icon: '📝', label: '加入便签', action: async () => {
      const selectedText = window.getSelection().toString();
      try {
        await addStickyNote(selectedText);
        utils.showNotification('已添加到便签');
      } catch (error) {
        console.error('添加便签失败:', error);
        utils.showNotification('添加便签失败', true);
      }
    }},
    { icon: '📝', label: '加入笔记', action: async () => {
      const selectedText = window.getSelection().toString().trim();
      try {
        await noteRepository.addNote(selectedText, true);
        utils.showNotification('已添加到笔记');
      } catch (error) {
        utils.showNotification('添加笔记失败', true);
      }
    }},
    { icon: '📋', label: '复制', action: () => {
      const selectedText = window.getSelection().toString();
      navigator.clipboard.writeText(selectedText)
        .then(() => utils.showNotification('已复制到剪贴板'))
        .catch(() => utils.showNotification('复制失败', true));
    }},
    { icon: '📤', label: '分享', action: () => {
      const selectedText = window.getSelection().toString();
      if (navigator.share) {
        navigator.share({
          title: document.title,
          text: selectedText,
          url: window.location.href
        }).catch(console.error);
      } else {
        navigator.clipboard.writeText(selectedText)
          .then(() => utils.showNotification('已复制到剪贴板'))
          .catch(() => utils.showNotification('复制失败', true));
      }
    }}
  ];

  buttons.forEach(({ icon, label, action }) => {
    const button = document.createElement('button');
    button.className = 'selection-menu-button';
    button.innerHTML = `<span class="icon">${icon}</span>${label}`;
    button.addEventListener('click', async (e) => {
      e.preventDefault();
      e.stopPropagation();
      await action();
      hideSelectionMenu();
    });
    menu.appendChild(button);
  });

  document.body.appendChild(menu);
  return menu;
}

// 显示选择菜单
function showSelectionMenu(x, y) {
  const menu = document.querySelector('.selection-menu') || createSelectionMenu();
  menu.style.left = `${x}px`;
  menu.style.top = `${y}px`;
  menu.classList.add('active');
}

// 隐藏选择菜单
function hideSelectionMenu() {
  const menu = document.querySelector('.selection-menu');
  if (menu) {
    menu.classList.remove('active');
  }
}

// 处理文本选择事件
document.addEventListener('mouseup', (e) => {
  const selection = window.getSelection();
  const selectedText = selection.toString().trim();

  if (selectedText && !e.target.closest('.selection-menu')) {
    const range = selection.getRangeAt(0);
    const rect = range.getBoundingClientRect();
    const scrollX = window.scrollX || window.pageXOffset;
    const scrollY = window.scrollY || window.pageYOffset;
    
    // 计算菜单位置，确保不会超出视窗
    const menuX = Math.min(
      scrollX + rect.left,
      scrollX + window.innerWidth - 200 // 假设菜单宽度约200px
    );
    const menuY = scrollY + rect.bottom + 10; // 在选中文本下方10px处显示

    showSelectionMenu(menuX, menuY);
  } else if (!e.target.closest('.selection-menu')) {
    hideSelectionMenu();
  }
});

// 点击其他地方时隐藏菜单
document.addEventListener('mousedown', (e) => {
  if (!e.target.closest('.selection-menu')) {
    hideSelectionMenu();
  }
});

// 滚动时隐藏菜单
document.addEventListener('scroll', () => {
  hideSelectionMenu();
}, true);

// Initialize global variables
window.selectedCompletedTodos = [];

// Add summary button update function
window.updateSummaryButton = () => {
  let container = document.querySelector('.todo-summary-container');
  if (!container) {
    container = document.createElement('div');
    container.className = 'todo-summary-container';
    document.body.appendChild(container);
  }

  if (window.selectedCompletedTodos?.length > 0) {
    let summaryButton = container.querySelector('.generate-summary-button');
    if (!summaryButton) {
      summaryButton = document.createElement('button');
      summaryButton.className = 'generate-summary-button';
      summaryButton.innerHTML = '📝 生成工作总结';
      summaryButton.addEventListener('click', generateTodoSummary);
      container.appendChild(summaryButton);
    }
  } else {
    container.innerHTML = '';
  }
};

// Generate summary function
async function generateTodoSummary() {
  if (!window.selectedCompletedTodos?.length) {
    utils.showNotification('请先选择已完成的待办事项', true);
    return;
  }

  const summaryButton = document.querySelector('.generate-summary-button');
  if (summaryButton.disabled) return; // 防止重复点击

  // 添加 loading 状态
  summaryButton.disabled = true;
  const originalText = summaryButton.innerHTML;
  summaryButton.innerHTML = '⌛️ 生成中...';

  const todoContents = window.selectedCompletedTodos.map(todo => todo.content).join('\n');
  const prompt = `请根据以下已完成的工作内容，生成一个简洁的工作总结。总结要突出重点，使用专业的语言，并按照工作类型进行分类整理：\n\n${todoContents}`;

  try {
    const response = await chrome.runtime.sendMessage({
      action: 'generateSummary',
      prompt: prompt
    });

    if (response.error) {
      utils.showNotification(response.error, true);
    } else {
      // 移除其他可能存在的总结模态框
      const existingModal = document.querySelector('.todo-summary-modal');
      if (existingModal) existingModal.remove();

      // Create a modal to display the summary
      const modal = document.createElement('div');
      modal.className = 'todo-summary-modal';
      modal.innerHTML = `
        <div class="todo-summary-content">
          <h3>工作总结</h3>
          <div class="summary-text">${response.summary.replace(/\n/g, '<br>')}</div>
          <div class="summary-actions">
            <button class="copy-summary">复制总结</button>
            <button class="add-to-sticky">加入便签</button>
            <button class="close-summary">关闭</button>
          </div>
        </div>
      `;
      document.body.appendChild(modal);

      // Add event listeners
      modal.querySelector('.copy-summary').addEventListener('click', () => {
        navigator.clipboard.writeText(response.summary);
        utils.showNotification('总结已复制到剪贴板');
      });

      modal.querySelector('.add-to-sticky').addEventListener('click', async () => {
        try {
          await stickyRepository.addStickyNote(response.summary);
          utils.showNotification('已添加到便签');
        } catch (error) {
          console.error('添加便签失败:', error);
          utils.showNotification('添加便签失败', true);
        }
      });

      modal.querySelector('.close-summary').addEventListener('click', () => {
        modal.remove();
      });

      // Clear selection
      window.selectedCompletedTodos = [];
      document.querySelectorAll('.todo-selection-checkbox').forEach(checkbox => {
        checkbox.checked = false;
      });
      window.updateSummaryButton();
    }
  } catch (error) {
    console.error('生成总结失败:', error);
    utils.showNotification('生成总结失败，请稍后重试', true);
  } finally {
    // 恢复按钮状态
    summaryButton.disabled = false;
    summaryButton.innerHTML = originalText;
  }
}

// Add modal styles
const style = document.createElement('style');
style.textContent = `
  .todo-summary-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 10003; /* 确保显示在待办弹窗之上 */
  }

  .todo-summary-content {
    background: white;
    padding: 24px;
    border-radius: 8px;
    max-width: 600px;
    width: 90%;
    max-height: 80vh;
    overflow-y: auto;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  }

  .todo-summary-content h3 {
    margin: 0 0 16px 0;
    color: #333;
  }

  .summary-text {
    white-space: pre-wrap;
    line-height: 1.6;
    color: #444;
    margin-bottom: 20px;
  }

  .summary-actions {
    display: flex;
    gap: 12px;
    justify-content: flex-end;
  }

  .summary-actions button {
    padding: 8px 16px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.2s ease;
  }

  .copy-summary, .add-to-sticky {
    background: #4CAF50;
    color: white;
  }

  .copy-summary:hover, .add-to-sticky:hover {
    background: #45a049;
  }

  .add-to-sticky {
    background: #2196F3;
  }

  .add-to-sticky:hover {
    background: #1976D2;
  }

  .close-summary {
    background: #f5f5f5;
    color: #666;
  }

  .close-summary:hover {
    background: #e0e0e0;
  }

  .generate-summary-button {
    transition: opacity 0.3s ease;
  }

  .generate-summary-button:disabled {
    opacity: 0.7;
    cursor: not-allowed;
  }
`;
document.head.appendChild(style);

